#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <math.h>
#include <string.h>


#define BUFSIZE 1024

int main(int argc,char **argv)
{
    int sfd;
    struct sockaddr_in raddr;//remote addr
    char rbuf[BUFSIZE];
    int len;

    if(argc < 2)
    {
    	fprintf(stderr,"Usage...\n");
    	exit(1);
    }
    
    sfd = socket(AF_INET,SOCK_STREAM,0/*IPPROTO_TCP*/);
    if(sfd < 0)
    {
    	perror("socket()");
    	exit(1);
    }

    raddr.sin_family = AF_INET;
    raddr.sin_port = htons(80);  //上网用的80端口
    inet_pton(AF_INET,argv[1],&raddr.sin_addr);

    if(connect(sfd,(void *)&raddr,sizeof(raddr)) < 0){
        perror("connect()");
        exit(1);
    }

    FILE *fp;
    fp = fdopen(sfd,"r+");  //提取文件描述符的FILE流
    if (fp == NULL){
        perror("fopen()");
        exit(1);
    }

    fprintf(fp,"GET /test.jpg\r\n\r\n");
    fflush(fp);  //刷新流
    
    while(1)
    {
    	len = fread(rbuf,1,BUFSIZE,fp);
    	if(len <= 0)
    		break;
    	fwrite(rbuf,1,len,stdout);
    }

    fclose(fp);

    exit(0);
}

